package com.hospital.controller;

import com.hospital.domain.DTO.ScheduleDTO;
import com.hospital.domain.pojo.Schedule;
import com.hospital.domain.utils.Result;
import com.hospital.service.ScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/schedule")
@Tag(name = "出诊安排接口", description = "无")
public class ScheduleController {
    private final ScheduleService scheduleService;

    @Operation(summary = "检验该医生当前时段预约情况")
    @GetMapping("/isFull")
    public Result isFull(Integer dId, String date, String time){
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
        Schedule schedule = scheduleService.lambdaQuery().eq(Schedule::getDId, dId).eq(Schedule::getDate, localDate).eq(Schedule::getTime, time).one();
        if(schedule == null || schedule.getRemain() == 0){
            return Result.fail("医生没排班或该时段已被约满");
        }
        return Result.ok();
    }

    @Operation(summary = "根据排班表查看医生出诊时间")
    @GetMapping("/time")
    public Result queryTime(@RequestParam("DId") Integer dId, @RequestParam("date") String date){
        if(dId == null){
            return Result.fail("服务器异常，请联系管理员");
        }
        LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println("查询排班 - 医生ID: " + dId + ", 日期: " + localDate);
        
        List<Schedule> schedules = scheduleService.lambdaQuery().eq(Schedule::getDId, dId).eq(Schedule::getDate, localDate).list();
        System.out.println("查询到排班数量: " + schedules.size());
        
        return Result.ok(schedules);
    }

    @Operation(summary = "管理员给医生排班（支持GET查询参数）")
    @GetMapping("/setSchedule")
    public Result setScheduleWithQuery(@RequestParam("dId") Integer dId,
                                       @RequestParam(value = "depId", required = false) Integer depIdLower,
                                       @RequestParam(value = "DepId", required = false) Integer depIdUpper,
                                       @RequestParam("date") String date,
                                       @RequestParam("time") String time){
        Integer depId = depIdLower != null ? depIdLower : depIdUpper;
        return scheduleService.setSchedule(dId, depId, date, time);
    }

    @Operation(summary = "管理员给医生排班（支持POST JSON）")
    @PostMapping("/setSchedule")
    public Result setSchedule(@RequestBody ScheduleDTO scheduleDTO){
        return scheduleService.setSchedule(scheduleDTO.getDId(), scheduleDTO.getDepId(), scheduleDTO.getDate(), scheduleDTO.getTime());
    }

    @Operation(summary = "获取所有排班信息")
    @GetMapping("/query")
    public Result queryAllSchedules(){
        return scheduleService.queryAllSchedules();
    }

    @Operation(summary = "根据医生ID获取排班信息")
    @GetMapping("/query/{dId}")
    public Result querySchedulesByDoctor(@PathVariable("dId") Integer dId){
        return scheduleService.querySchedulesByDoctor(dId);
    }
    
    @Operation(summary = "获取所有排班信息（包含医生信息）")
    @GetMapping("/queryWithDoctorInfo")
    public Result queryAllSchedulesWithDoctorInfo(){
        return scheduleService.queryAllSchedulesWithDoctorInfo();
    }

    @Operation(summary = "根据医生ID获取排班信息（包含医生信息）")
    @GetMapping("/queryWithDoctorInfo/{dId}")
    public Result querySchedulesByDoctorWithInfo(@PathVariable("dId") Integer dId){
        return scheduleService.querySchedulesByDoctorWithInfo(dId);
    }

    @Operation(summary = "获取医生所有排班信息")
    @GetMapping("/all")
    public Result getAllSchedulesByDoctor(@RequestParam("DId") Integer dId){
        if(dId == null){
            return Result.fail("医生ID不能为空");
        }
        System.out.println("查询医生所有排班 - 医生ID: " + dId);
        
        List<Schedule> schedules = scheduleService.lambdaQuery()
                .eq(Schedule::getDId, dId)
                .orderByDesc(Schedule::getDate)
                .orderByAsc(Schedule::getTime)
                .list();
        
        System.out.println("查询到排班总数: " + schedules.size());
        return Result.ok(schedules);
    }

    @Operation(summary = "创建测试排班数据")
    @PostMapping("/createTestData")
    public Result createTestData(@RequestParam("dId") Integer dId, @RequestParam("date") String date){
        try {
            LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
            
            // 创建上午排班
            Schedule morningSchedule = new Schedule(dId, 1, localDate, "上午", 10, 0);
            scheduleService.save(morningSchedule);
            
            // 创建下午排班
            Schedule afternoonSchedule = new Schedule(dId, 1, localDate, "下午", 8, 0);
            scheduleService.save(afternoonSchedule);
            
            return Result.ok("测试排班数据创建成功");
        } catch (Exception e) {
            return Result.fail("创建测试数据失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新排班信息")
    @PutMapping("/update")
    public Result updateSchedule(@RequestBody ScheduleDTO scheduleDTO){
        return scheduleService.updateSchedule(scheduleDTO);
    }

    @Operation(summary = "删除排班")
    @DeleteMapping("/delete/{sId}")
    public Result deleteSchedule(@PathVariable("sId") Integer sId){
        return scheduleService.deleteSchedule(sId);
    }
}
